package com.wnx.job.modules.jms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.wnx.job.common.api.Const;
import com.wnx.job.common.api.PageResult;
import com.wnx.job.common.api.QueryPageBean;
import com.wnx.job.common.exception.Asserts;
import com.wnx.job.common.utils.StrUtils;
import com.wnx.job.modules.jms.dto.CompanyParam;
import com.wnx.job.modules.jms.mapper.JmsCompanyMapper;
import com.wnx.job.modules.jms.model.JmsCompany;
import com.wnx.job.modules.jms.model.JmsPost;
import com.wnx.job.modules.jms.service.JmsCompanyService;
import com.wnx.job.modules.jms.service.JmsPostService;
import com.wnx.job.modules.ums.dto.UmsAdminParam;
import com.wnx.job.modules.ums.model.UmsAdmin;
import com.wnx.job.modules.ums.service.UmsAdminService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 企业 服务实现类
 * </p>
 *
 * @author wangnaixing
 * @since 2021-12-17
 */
@Service
public class JmsCompanyServiceImpl extends ServiceImpl<JmsCompanyMapper, JmsCompany> implements JmsCompanyService {
    private static final String COMPANY_PREFIX = "GS";
    @Resource
    private JmsCompanyMapper companyMapper;
    @Resource
    private JmsPostService postService;
    @Resource
    private UmsAdminService adminService;



    /**
     * 根据ID查询企业详情
     * @param id
     * @return
     */
    @Override
    public CompanyParam findDetailById(Long id) {
        return companyMapper.findDetailById(id);
    }

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult<JmsCompany> findByPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        List<JmsCompany> companyList = companyMapper.findByCondition(queryPageBean.getQueryParams());
        return PageResult.restPage(companyList);
    }

    /**
     * 根据账号查询公司信息
     * @param username
     * @return
     */
    @Override
    public JmsCompany findByUsername(String username) {
        return companyMapper.selectOne(new QueryWrapper<JmsCompany>().eq("account",username));
    }

    /**
     *  新增企业信息
     * @param tbCompany
     */
    @Override
    public void saveCompany(JmsCompany tbCompany) {
        //校验:邮箱唯一性
        JmsCompany tbCompanyByDb = this.findByEmail(tbCompany.getEmail());
        if (tbCompanyByDb != null){
            Asserts.fail("该邮箱已经被使用了，请更换!!!");
        }

        tbCompany.setAccount(COMPANY_PREFIX+ StrUtils.randomCode());
        tbCompany.setStatus(Const.COMPANY_PRE_REVIEW);
        tbCompany.setCreated(new Date());
        tbCompany.setEmailStatus(Const.SEND_COMPANY_PASS_EMAIL_NO);

        //调用持久层，新增企业
        companyMapper.insert(tbCompany);

    }

    /**
     * 删除企业
     * @param id
     */
    @Override
    public void deleteCompany(Long id) {
        //校验：删除企业之前确保没有关联的职位信息
        JmsCompany companyByDb = companyMapper.selectById(id);
        long postCount =  findPostCountByCompanyId(id);
        if (postCount > 0){
            Asserts.fail("该公司还存在有发布的职位信息，请先删除该公司职位信息。");
        }


        //删除企业拥有的账号
        UmsAdmin userByDb = adminService.getAdminByUsername(companyByDb.getAccount());
        adminService.delete(userByDb.getId());
        companyMapper.deleteById(id);


    }

    /**
     * 企业审核通过
     * @param company
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkPass(JmsCompany company) {
        //校验：公司是否已经审核通过
        if (company.getStatus() == Const.COMPANY_PRE_REVIEW){
            //构造用户对象，调用持久层添加用户信息。
            UmsAdminParam admin = new UmsAdminParam();
            admin.setUsername(company.getAccount());
            admin.setPassword(Const.DEFAULT_PASSWORD);
            admin.setIcon(Const.DEFAULT_AVATAR);
            admin.setNickName(company.getContact());
            admin.setEmail(company.getEmail());
            admin.setNote(Const.DEFAULT_NOTE_COMPANY);
            UmsAdmin register = adminService.register(admin);
            //分配企业用户，企业角色
            adminService.updateRole(register.getId(), Collections.singletonList(Const.ROLE_COMPANY));
            company.setStatus(Const.COMPANY_REVIEWED);
            companyMapper.updateById(company);
        }else {
            Asserts.fail("此公司已经审核过了请不要重复审核");
        }



    }

    /**
     * 企业审核不通过
     * @param company
     */
    @Override
    public void checkRefuse(JmsCompany company) {
        //设置公司审核状态为2，表审核不通过。
        company.setStatus(Const.COMPANY_REJECT_REVIEW);

        //调用持久层，修改企业
        companyMapper.updateById(company);
    }

    /**
     * 根据企业ID查询职位数量
     * @param companyId
     * @return
     */
   private long findPostCountByCompanyId(Long companyId){
      return   postService.count(new QueryWrapper<JmsPost>().eq("company_id",companyId));
   }



    /**
     * 根据企业邮箱查询企业信息
     * @param email
     * @return
     */
    private JmsCompany findByEmail(String email){
        return companyMapper.selectOne(new QueryWrapper<JmsCompany>().eq("email",email));
    }
}
